package de.suur.jarmi.client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import de.suur.jarmi.common.Compressor;
import de.suur.jarmi.common.JarmiException;
import de.suur.jarmi.common.Serializer;

public class JarmiHttpClient extends JarmiClient {

	private String host;
	private String path;
	private int port;

	public JarmiHttpClient(Class<?> serviceInterface, Compressor compressor,
			Serializer serializer, String host, int port, String path) {
		super(serviceInterface, compressor, serializer);
		this.host = host;
		this.port = port;
		this.path = path;
	}

	@Override
	protected byte[] request(byte[] requestData) {
		try {
			URL url = new URL("http://" + host + ":" + port
					+ (path.startsWith("/") ? "" : "/") + path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestProperty("Content-Type",
					"application/octet-stream");

			sendRequest(requestData, connection.getOutputStream());
			byte[] response = receiveResponse(connection.getInputStream());
			return response;
		} catch (IOException e) {
			throw new JarmiException(e);
		}
	}

}
